package io.renren.modules.basic.controller;




import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.utils.R;
import io.renren.modules.basic.entity.*;
import io.renren.modules.basic.service.*;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.work.Utils.ManageConstant;
import io.renren.modules.work.Utils.ManagePublicMethod;
import io.renren.modules.work.service.WorkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-10-14 10:50:42
 */
@Api(description = "任务接口")
@RestController
@RequestMapping(value = "generator/mtcctaskruninfo")
public class MtCcTaskRunInfoController extends AbstractController {
    @Autowired
    private MtCcTaskRunInfoService mtCcTaskRunInfoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private MtCcTaskRunInfoLogService mtCcTaskRunInfoLogService;
    @Autowired
    private MtCcTaskRunInfoDetService mtCcTaskRunInfoDetService;
    @Autowired
    private MtCcTaskRunInfoDetLogService mtCcTaskRunInfoDetLogService;
    @Autowired
    private MtCcProductService mtCcProductService;
    @Autowired
    private MtCcWarehousPositionRelatService mtCcWarehousPositionRelatService;
    @Autowired
    private WorkService workService;
    @Autowired
    private MtCcTaskRunInfoDetController mtCcTaskRunInfoDetController;

    /**
     * 列表
     */
    @ApiOperation(value = "任务列表",notes = "任务列表")
    @RequestMapping("/list")
    @RequiresPermissions("generator:mtcctaskruninfo:list")
    public R list(@RequestParam Map<String, Object> params){

        List<MtCcTaskRunInfoEntity> list = mtCcTaskRunInfoService.queryPage(params);

        return R.ok().put("list", list);
    }

    /**
     * 重置正在执行的任务
     */
    @ApiOperation(value = "重置正在执行的任务",notes = "重置正在执行的任务")
    @RequestMapping("/resetTask")
    public R resetTask(@RequestParam Map<String, Object> params){
        MtCcTaskRunInfoEntity taskInfoId = mtCcTaskRunInfoService.getOne(new QueryWrapper<MtCcTaskRunInfoEntity>().eq("status", 1));
        List<MtCcTaskRunInfoDetEntity> mtCcTaskRunInfoDetEntities = mtCcTaskRunInfoDetService.list(new QueryWrapper<MtCcTaskRunInfoDetEntity>().eq("task_run_id", taskInfoId.getId()).eq("status",1));
        for (MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity:mtCcTaskRunInfoDetEntities
             ) {
            mtCcTaskRunInfoDetEntity.setStatus(0);
            mtCcTaskRunInfoDetService.updateById(mtCcTaskRunInfoDetEntity);
        }
        taskInfoId.setStatus(0);
        mtCcTaskRunInfoService.updateById(taskInfoId);

        return R.ok();
    }

    /**
     * 列表
     */
    @ApiOperation(value = "根据编码模糊查询",notes = "根据编码模糊查询")
    @RequestMapping("/getLikeList")
    public List getLikeList(@RequestParam Map<String, Object> params){
        String code = String.valueOf(params.get("key"));
        List<MtCcProductEntity> mtCcProductEntityList = mtCcProductService.list(new QueryWrapper<MtCcProductEntity>().likeRight("product_code", code));
        List<String> list=new ArrayList();
        for (MtCcProductEntity mtCcProductEntity :mtCcProductEntityList
                ) {
            String productCode = mtCcProductEntity.getProductCode();
            list.add(productCode);
        }
        return list;
    }
    /**
     * 信息
     */
    @ApiOperation(value = "任务详情",notes = "任务详情")
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:mtcctaskruninfo:info")
    public R info(@PathVariable("id") Integer id){
		MtCcTaskRunInfoEntity mtCcTaskRunInfo = mtCcTaskRunInfoService.getById(id);

        return R.ok().put("mtCcTaskRunInfo", mtCcTaskRunInfo);
    }

    /**
     * 保存
     * 参数：
     *      任务类型taskType
     *      产品id,型号，数量，单位
     */
    @ApiOperation(value = "新增任务",notes = "新增任务")
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("generator:mtcctaskruninfo:save")
    public R save(@RequestBody MtCcTaskRunInfoEntity mtCcTaskRunInfo){
        SysUserEntity user=this.getUser();
        String doorWay = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_id", user.getUserId())).getDoorWay();
        MtCcProductEntity productEntity =new MtCcProductEntity();
        try {
            productEntity = mtCcProductService.getOne(new QueryWrapper<MtCcProductEntity>().eq("product_code", mtCcTaskRunInfo.getModel()));
        }catch (Exception e){
            return R.error("该物料编码错误或不存在于数据库中，请核对后重试！");
        }
        if(mtCcTaskRunInfo.getTaskType()==0){//出库


            List<MtCcWarehousPositionRelatEntity> mtCcWarehousPositionRelats = mtCcWarehousPositionRelatService.list(new QueryWrapper<MtCcWarehousPositionRelatEntity>().eq("product_id", productEntity.getId()));
            int num=0;
            for (MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity:mtCcWarehousPositionRelats) {
                num = num + mtCcWarehousPositionRelatEntity.getQuantity();
                if (num >= Integer.parseInt(mtCcTaskRunInfo.getNum())) {
                    break;
                }
            }
            if (num<Integer.parseInt(mtCcTaskRunInfo.getNum())){
                return R.error("仓库中"+productEntity.getProductName()+"数量为"+num+",你要出库的数量为"+mtCcTaskRunInfo.getNum()+",仓库数量不够出库！");
            }

            /**
             * 1.把手动下的主任务存到数据库中
             */
            mtCcTaskRunInfo.setCreateTime(new Date());
            mtCcTaskRunInfo.setUserId(Integer.parseInt(String.valueOf(user.getUserId())));
            mtCcTaskRunInfo.setUserName(user.getUsername());
            mtCcTaskRunInfo.setTaskType(0);
            mtCcTaskRunInfo.setStatus(0);
            mtCcTaskRunInfo.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.OUT_STOCK_ORDER_TYPE,doorWay));
            mtCcTaskRunInfo.setProductId(productEntity.getId());
            mtCcTaskRunInfo.setModel(productEntity.getProductCode());
            mtCcTaskRunInfo.setSpecModel(productEntity.getSpecModel());
            mtCcTaskRunInfo.setUnit(productEntity.getUnitName());
            mtCcTaskRunInfo.setSource(user.getUsername());
            mtCcTaskRunInfoService.save(mtCcTaskRunInfo);
            mtCcTaskRunInfo.setOrderNum(mtCcTaskRunInfo.getId());
            mtCcTaskRunInfoService.updateById(mtCcTaskRunInfo);
            //出库自动分配子任务
            Map<String,Object> params=new HashMap();
            params.put("productId",productEntity.getId());
            params.put("checkOutNum",mtCcTaskRunInfo.getNum());
            params.put("doorWay",mtCcTaskRunInfo.getTaskCode().substring(1,3));
            params.put("id",mtCcTaskRunInfo.getId());
            if ("".equals(mtCcTaskRunInfo.getDateNum())||mtCcTaskRunInfo.getDateNum()==null){
                params.put("dateNum","");
            }else {
                params.put("dateNum",mtCcTaskRunInfo.getDateNum());
            }

            workService.checkOutMainTaskForDet(params);

            /**
             * 2.把手动下的主任务的日志存到数据库
             */

        }else if (mtCcTaskRunInfo.getTaskType()==1){
            mtCcTaskRunInfo.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,doorWay));
            mtCcTaskRunInfo.setCreateTime(new Date());
            mtCcTaskRunInfo.setUserId(Integer.parseInt(String.valueOf(user.getUserId())));
            mtCcTaskRunInfo.setUserName(user.getUsername());
            mtCcTaskRunInfo.setSource(user.getUsername());
            mtCcTaskRunInfo.setSpecModel(productEntity.getSpecModel());
            mtCcTaskRunInfo.setProductId(productEntity.getId());
            mtCcTaskRunInfo.setUnit(mtCcProductService.getOne(new QueryWrapper<MtCcProductEntity>().eq("product_code",mtCcTaskRunInfo.getModel())).getUnitName());
            mtCcTaskRunInfo.setStatus(0);
            mtCcTaskRunInfoService.save(mtCcTaskRunInfo);
            mtCcTaskRunInfo.setOrderNum(mtCcTaskRunInfo.getId());
            mtCcTaskRunInfoService.updateById(mtCcTaskRunInfo);
        }


		//添加日志
        MtCcTaskRunInfoLogEntity mtCcTaskRunInfoLogEntity=new MtCcTaskRunInfoLogEntity();
        mtCcTaskRunInfoLogEntity.setCreateTime(mtCcTaskRunInfo.getCreateTime());
        mtCcTaskRunInfoLogEntity.setUserId(mtCcTaskRunInfo.getUserId());
        mtCcTaskRunInfoLogEntity.setUserName(mtCcTaskRunInfo.getUserName());
        mtCcTaskRunInfoLogEntity.setTaskType(mtCcTaskRunInfo.getTaskType());
        mtCcTaskRunInfoLogEntity.setTaskCode(mtCcTaskRunInfo.getTaskCode());
        mtCcTaskRunInfoLogEntity.setProductId(mtCcTaskRunInfo.getProductId());
        mtCcTaskRunInfoLogEntity.setModel(mtCcTaskRunInfo.getModel());
        mtCcTaskRunInfoLogEntity.setNum(mtCcTaskRunInfo.getNum());
        mtCcTaskRunInfoLogEntity.setUnit(mtCcTaskRunInfo.getUnit());
        mtCcTaskRunInfoLogEntity.setDateNum(mtCcTaskRunInfo.getDateNum());
        mtCcTaskRunInfoLogEntity.setRemarks(mtCcTaskRunInfo.getRemarks());
        mtCcTaskRunInfoLogService.save(mtCcTaskRunInfoLogEntity);
        return R.ok();

    }

    /**
     * 修改
     */
    @ApiOperation(value = "修改任务",notes = "修改任务")
    @RequestMapping("/update")
    @RequiresPermissions("generator:mtcctaskruninfo:update")
    public R update(@RequestBody MtCcTaskRunInfoEntity mtCcTaskRunInfo){
        mtCcTaskRunInfo.setUpdateTime(new Date());
		mtCcTaskRunInfoService.updateById(mtCcTaskRunInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除任务",notes = "删除任务")
    @RequestMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("generator:mtcctaskruninfo:delete")
    public R delete(@RequestBody Integer id){
        MtCcTaskRunInfoEntity mtCcTaskRunInfo = mtCcTaskRunInfoService.getById(id);
        /*MtCcTaskRunInfoLogEntity mtCcTaskRunInfoLog = mtCcTaskRunInfoLogService
                .getOne(new QueryWrapper<MtCcTaskRunInfoLogEntity>()
                        .eq("task_code", mtCcTaskRunInfo.getTaskCode()));
        //修改日志，状态改为3-取消执行
        mtCcTaskRunInfoLog.setStatus(3);
        mtCcTaskRunInfoLogService.updateById(mtCcTaskRunInfoLog);*/
        List<MtCcTaskRunInfoDetEntity> mtCcTaskRunInfoDetEntities = mtCcTaskRunInfoDetService
                .list(new QueryWrapper<MtCcTaskRunInfoDetEntity>().eq("task_run_id", id).in("status",0,1));
        if (mtCcTaskRunInfoDetEntities.size()!=0){
            List ids=new ArrayList();
            for (MtCcTaskRunInfoDetEntity mtCcTaskRunInfoDetEntity :mtCcTaskRunInfoDetEntities
                    ) {
                mtCcTaskRunInfoDetController.delete(mtCcTaskRunInfoDetEntity.getId());
            }
        }//删除对应主任务下的子任务
        /*List<MtCcTaskRunInfoDetLogEntity> mtCcTaskRunInfoLogDetEntitis = mtCcTaskRunInfoDetLogService
                .list(new QueryWrapper<MtCcTaskRunInfoDetLogEntity>().eq("task_run_id", id));
        if (mtCcTaskRunInfoLogDetEntitis.size()!=0){
            for (int i=0;i<mtCcTaskRunInfoDetEntities.size();i++){
                MtCcTaskRunInfoDetLogEntity mtCcTaskRunInfoDetLogEntity = mtCcTaskRunInfoLogDetEntitis.get(i);
                mtCcTaskRunInfoDetLogEntity.setStatus(3);
                mtCcTaskRunInfoDetLogService.updateById(mtCcTaskRunInfoDetLogEntity);
            }
        }*///修改子任务日志表中的对应子任务状态为取消执行
        mtCcTaskRunInfoService.removeById(id);

        return R.ok();
    }

    /**
     * 排序
     */
    @ApiOperation(value = "排序任务",notes = "排序任务")
    @PostMapping("/sort")
    public R sort(@RequestBody List<MtCcTaskRunInfoEntity> mtCcTaskRunInfoEntities){
        mtCcTaskRunInfoService.saveOrUpdateBatch(mtCcTaskRunInfoEntities);
        //List<MtCcTaskRunInfoEntity> list = mtCcTaskRunInfoService.list(new QueryWrapper<MtCcTaskRunInfoEntity>().orderBy(false, false, "order_num"));
        return R.ok();
    }
    /**
     * 执行主任务
     */
    @ApiOperation(value = "执行主任务",notes = "执行主任务")
    @PostMapping("/runTask/{id}")
    public R runTask(@PathVariable("id") Integer id){
        int count = mtCcTaskRunInfoService.count(new QueryWrapper<MtCcTaskRunInfoEntity>().eq("status", 1));
        if (count>0){
            return R.error("当前有其他任务正在执行,请稍后重试...");
        }
        MtCcTaskRunInfoEntity mtCcTaskRunInfoEntity = mtCcTaskRunInfoService.getById(id);
        mtCcTaskRunInfoEntity.setStatus(1);
        mtCcTaskRunInfoService.updateById(mtCcTaskRunInfoEntity);
        return R.ok("本条主任务开始执行,请选择子任务!");
    }
}
